package com.lepu.app.usercenter;

import lib.share.login.LoginLib;
import lib.share.login.OnLoginListener;
import lib.share.login.UserInfo;

import org.json.JSONException;
import org.json.JSONObject;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.AppEnterTongJi;
import com.app.utils.Const;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.core.HttpRequest;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.geneal.UploadMenuImage;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.eyzhs.app.R;
import com.lepu.app.fun.grow.fragment.FragmentGrow;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.main.permission.PermissionUtil;
import com.lepu.app.main.permission.callback.PermissionResultCallBack;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.usercenter.util.UserCenterUtil;

public class LoginActivity extends BaseFragmentActivity implements
		AsyncRequest, OnEditorActionListener, OnLoginListener {

	private static final String REQUEST_LOGIN = "request_login";
	private static final String REQUEST_LOGIN_THIRD = "request_login_third";

	private static final int MSG_LOGIN_SUCCESS = 10;
	private static final int MSG_LOGIN_FAIL = 11;
	
	private static final int MSG_LOGIN_THIRD_SUCCESS = 20;
	private static final int MSG_LOGIN_THIRD_FAIL = 21;
	
	private int mCurrentLoginType = 0;
	private UserInfo mThirdLoginUserInfo = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usercenter_login_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}

	/**
	 * 初始化方法
	 */
	private void init() {

		TextView closeTextView = (TextView) findViewById(R.id.closeTextView);
		closeTextView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finishAnim(R.anim.lib_push_down_up_in,
						R.anim.lib_push_down_up_out);
			}
		});

		Button loginButton = (Button) findViewById(R.id.loginButton);
		TextView registerTextView = (TextView) findViewById(R.id.registerTextView);
		TextView forgetPwdTextView = (TextView) findViewById(R.id.forgetPwdTextView);

		loginButton.setOnClickListener(mOnClickListener);
		registerTextView.setOnClickListener(mOnClickListener);
		forgetPwdTextView.setOnClickListener(mOnClickListener);

		LinearLayout contentLayout = (LinearLayout) findViewById(R.id.contentLayout);
		contentLayout.setOnTouchListener(new View.OnTouchListener() {

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				UtilityBase.closeSoftInput(LoginActivity.this);
				return false;
			}
		});

		EditText pwdEditText = (EditText) findViewById(R.id.pwdEditText);
		pwdEditText.setOnEditorActionListener(this);

		LinearLayout loginWXLayout = (LinearLayout) findViewById(R.id.loginWXLayout);
		LinearLayout loginQQLayout = (LinearLayout) findViewById(R.id.loginQQLayout);
		LinearLayout loginSinaWeiboLayout = (LinearLayout) findViewById(R.id.loginSinaWeiboLayout);

		loginWXLayout.setOnClickListener(mOtherLoginClickListener);
		loginQQLayout.setOnClickListener(mOtherLoginClickListener);
		loginSinaWeiboLayout.setOnClickListener(mOtherLoginClickListener);
		
		//检查微信是否安装了
		boolean flag = AppManager.checkIfInstallApplication(this, "com.tencent.mm");
		if(!flag)
		{
			loginWXLayout.setVisibility(View.GONE);
		}

		//checkPermisson();
	}

	public UserInfo getThirdUserInfo()
	{
		return mThirdLoginUserInfo;
	}
	
	public int getThirdLoginType()
	{
		return mCurrentLoginType;
	}

	private void login() {
		EditText userEditText = (EditText) findViewById(R.id.userEditText);
		EditText pwdEditText = (EditText) findViewById(R.id.pwdEditText);

		String userContent = userEditText.getText().toString().trim();
		String pwdContent = pwdEditText.getText().toString().trim();

		boolean flag = UserCenterUtil.login(this, this, REQUEST_LOGIN,
				userContent, pwdContent);
		if (flag) {
			showProgressDialog();
		}
	}

	View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = null;

			switch (v.getId()) {
			case R.id.loginButton:
				login();

				break;
			case R.id.registerTextView:

				AppEnterTongJi.clickEvent(73, "");
				
				intent = new Intent(LoginActivity.this, RegisterActivity.class);
				startActivityAnim(intent, R.anim.lib_push_down_up_in,
						R.anim.lib_push_down_up_out);
				break;
			case R.id.forgetPwdTextView:

				intent = new Intent(LoginActivity.this, ForgetPwdActivity.class);
				startActivity(intent, true);
				break;

			default:
				break;
			}
		}
	};

	/*
	 * 第三方登录
	 */
	View.OnClickListener mOtherLoginClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View view) {
			LoginLib loginLib = LoginLib.getInstance(LoginActivity.this);
			loginLib.setOnLoginListener(LoginActivity.this);

			int rid = view.getId();
			switch (rid) {
			case R.id.loginWXLayout:
				mCurrentLoginType = LoginLib.TYPE_LOGIN_WX;
				loginLib.loginWeixin();
				break;
			case R.id.loginQQLayout:
				mCurrentLoginType = LoginLib.TYPE_LOGIN_QQ;
				loginLib.loginQQ();
				break;
			case R.id.loginSinaWeiboLayout:
				mCurrentLoginType = LoginLib.TYPE_LOGIN_WEIBO;
				loginLib.loginSinaWeibo();
				break;

			default:
				break;
			}
		}
	};

	private void updateAlbumData() {
		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		// album name
		if (!TextUtils.isEmpty(loginInfo.AlbumName)) {
			UserConfig.setConfig(this, Const.CONFIG_APP_ALBUM_NAME,
					loginInfo.AlbumName);
		}

		// album music
		if (!TextUtils.isEmpty(loginInfo.AlbumMusicID)) {
			UserConfig.setConfig(this, Const.SETTING_MUSIC_INDEX_SELECTED,
					UtilityBase.parseInt(loginInfo.AlbumMusicID));
		}

		// album cover
		if (!TextUtils.isEmpty(loginInfo.AlbumCoverURL)) {
			final String coverPath = SdLocal.getAlbumUserPath(this,
					loginInfo.UserID, "album_cover");
			final String url = Setting.getImageUrl(loginInfo.AlbumCoverURL);

			new Thread(new Runnable() {

				@Override
				public void run() {
					HttpRequest.downloadFileBy(url, coverPath, new CallBack() {

						@Override
						public void callBackFail(Object obj) {
							super.callBackFail(obj);
							LogUtilBase.LogD(null, "download album_cover fail");
						}

						@Override
						public void callBackSuccess(Object obj) {
							super.callBackSuccess(obj);
							LogUtilBase.LogD(null,
									"download album_cover success");

							FragmentGrow instance = FragmentGrow.getInstance();
							if (instance != null) {
								instance.mHandler
										.sendEmptyMessage(FragmentGrow.MSG_UPDATE_ALBUM_COVER);
							}
						}
					});
				}
			}).start();
		}
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_LOGIN_SUCCESS:
			case MSG_LOGIN_THIRD_SUCCESS:

				hideProgressDialog();

				if (MyApplication.getInstance().checkIsLogin()) {

					// 更新相册内容
					updateAlbumData();

					// 登录成功更新
					MainTabActivity.getInstance().mHandler
							.sendEmptyMessage(MainTabActivity.MSG_LOGIN_UPDATE);

					finishAnim(R.anim.lib_push_down_up_in,
							R.anim.lib_push_down_up_out);
				} else {
					// UIHelper.showToast(getApplicationContext(), "登录失败");
				}

				break;
			case MSG_LOGIN_FAIL:

				hideProgressDialog();
				break;
			case MSG_LOGIN_THIRD_FAIL:

				hideProgressDialog();
				
				int code = msg.arg1;
				if(code == 110)
				{
					//110-未绑定，请在设置昵称后绑定账号登录
					Intent intent = new Intent(LoginActivity.this,UserModifyNameActivity.class
							);
					intent.putExtra("ThirdLoginModifyNickName", true);
					intent.putExtra("NickName", mThirdLoginUserInfo.userName);
					startActivityAnim(intent,R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
				}
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_LOGIN) || object.equals(REQUEST_LOGIN_THIRD)) {

			String result = (String) data;
			JSONObject dataObject = null;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				dataObject = (JSONObject) obj1.get("DetailInfo");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			LoginInfo loginInfo = LoginInfo.parseLoginInfo(dataObject
					.toString());
			LoginInfo.saveLoginInfo(this, loginInfo);

			mHandler.sendEmptyMessage(MSG_LOGIN_SUCCESS);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_LOGIN)) {
			mHandler.sendEmptyMessage(MSG_LOGIN_FAIL);
		}else if (object.equals(REQUEST_LOGIN_THIRD)) {
			
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(errorMessage);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_LOGIN_THIRD_FAIL;
			msg.arg1 = code;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_DONE:

			login();
			break;
		}
		return true;
	}

	@Override
	public void onSignUp(UserInfo info) {

		if (info != null) {
			LogUtilBase.LogD(null, info.toString());
			mThirdLoginUserInfo = info;

			showProgressDialog(false);
			UserCenterUtil.thirdLogin(this, this, REQUEST_LOGIN_THIRD, info.userId,
					mCurrentLoginType, info.userToken,
					String.valueOf(info.userExpiresTime));
		}
	}

}
